<?php

/**
 * Contact Controller.
 * 
 * @author james
 *
 */
class ContactController extends Zend_Controller_Action {
	
	private $_userRelation;
	
	public function init() {
		$this->_userRelation = new UserRelation();
	}
	
	/**
	 * Action for index.
	 */
	public function indexAction() {
		$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if(!$data){
			$this->_redirect('user/login');
		} else {
			
			
		}
	}
	
	/**
	 * My contact page action.
	 */
	public function mycontactAction() {
		$loginUser = $this->_helper->user->getUserData();
		if (isset($loginUser)) {
			$users = User::getContacts(User::findById($loginUser->id));
			$contacts = array();
			foreach ($users as $user) {
				$userRelation = UserRelation::findUnique($loginUser->id, $user->id, 1);
				$contact = new Custom_Contact($user->id, $user->email, $user->username, $userRelation->alias);
				$contacts[$user->id] = $contact;
			}
			
			$this->view->paginator = $this->_helper->paginator($this->_getParam('page', 1), $contacts);
//			$this->view->contacts = $contacts;
		} else {
			echo 'No permission';
		}
	}
	
	/**
	 * User relation edit action.
	 */
	public function editAction() {
		$user = $this->_helper->user->getUserData();
		if (isset($user)) {
			$original_user_id = $user->id;
			$potentical_user_id = $this->getRequest()->getParam('id');
			$userRelation = UserRelation::findUnique($original_user_id, $potentical_user_id, 1);
			$editContactForm = new EditContactForm($userRelation);
			$this->view->form = $editContactForm;
			if ($this->getRequest ()->isPost ()) {
				if ($editContactForm->isValid($_POST)) {
					$original_user_id = $editContactForm->getValue('original_user_id');
					$potential_user_id = $editContactForm->getValue('potential_user_id');
					$alias = $editContactForm->getValue('alias');
					$data = array(
						'original_user_id'=>$original_user_id,
						'potential_user_id'=>$potential_user_id,
						'relation_type'=>1,
						'alias'=>$alias,
						'created'=>$this->_helper->generator->generateCurrentTime()
					);
					UserRelation::addOrUpdateUserRelation($data);
					$this->_redirect('contact/mycontact');
				}
			}
		} else {
			echo 'No permission';
		}
	}
	
	/**
	 * Delete contact action.
	 */
	public function deleteAction() {
		$user = $this->_helper->user->getUserData();
		if (isset($user)) {
			$original_user_id = $user->id;
			$potentical_user_id = $this->getRequest()->getParam('id');
			UserRelation::deleteUserRelation($original_user_id, $potentical_user_id, 1);
			$this->_redirect('contact/mycontact');
		} else {
			echo 'No permission';
		}
	}
}

?>